package com.authine.cloudpivot.ext.task;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author hxd
 * @Date 2021/11/11 13:45
 * @Description
 **/
@Slf4j
public class TaskDelayedManager {

    private static DelayQueue<TaskDelayed> taskQueue = new DelayQueue<>();


    //剩余任务数
    private static AtomicInteger count = new AtomicInteger(0);
    //加入任务数
    private static AtomicInteger total = new AtomicInteger(0);
    //执行任务数
    private static AtomicInteger decrementTotal = new AtomicInteger(0);

    //最小线程0,最大10,空闲线程存活20秒
    private static  ExecutorService exec = new ThreadPoolExecutor(0, 50,
            20L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());

    /**
     *  添加任务
     * @param runnable
     * @param time
     * @param unit
     */
    public static void put( Runnable runnable,  long time, TimeUnit unit){
        long timeout = TimeUnit.MILLISECONDS.convert(time, unit);
        TaskDelayed taskDelayed = new TaskDelayed(runnable, timeout+System.currentTimeMillis() );

        taskQueue.put(taskDelayed);
        int i = count.incrementAndGet();

        if (log.isDebugEnabled()){
            int j = total.incrementAndGet();
            log.debug("=========延时任务总数:{},当前数量:{}",j,i);
        }

        if (i==1){
            log.info("=========延时任务开始执行 ");
            init();
        }

    }

    /**
     *  初始化执行任务
     */
    private static void init()  {
        System.out.println("=================task类型初始化....");
        exec.execute(TaskDelayedManager::execute);
    }
    private static void execute()  {
        log.info("===============守护线程启动,thread:{}",Thread.currentThread().getName());
        boolean flag = true;
        int i;
        int j=0;

        while (flag){
            try {
                TaskDelayed take = taskQueue.take();
                if (take == null) {
                    continue;
                }
                i = count.decrementAndGet();

                if (log.isDebugEnabled()) {
                    j = decrementTotal.incrementAndGet();
                }

                if (i == 0) {
                    flag = false;

                    if (log.isDebugEnabled()) {
                        total.set(0);
                        decrementTotal.set(0);
                        log.debug("=========延时任务准备结束,已执行任务数:{},thread:{}",j,Thread.currentThread().getName());
                    }

                }
                if (log.isDebugEnabled()){
                    log.debug("===========延时任务,获取到任务准备执行,剩余任务数:{},thread:{}",i,Thread.currentThread().getName());
                    log.debug("=================延时任务,任务设置执行时间:{},当前时间:{}",take.getExcuteTime(),System.currentTimeMillis());
                }
                exec.execute(take.getRunnable());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
